<?php

namespace app\api\controller\v1;

use app\api\controller\Intel as BaseIntel;
use app\common\model\app\IntelTopic as TopicModel;
use think\Validate;
use think\Db;
use think\Cache;
use think\Queue;

/**
 * App情报管理
 *
 * @icon fa fa-circle-o
 */
class Intel extends BaseIntel
{

    /**
     * AppIntel模型对象
     * @var \app\common\model\app\Intel
     */
    protected $model = null;
    protected $redis = null;
    protected $noNeedLogin = ['list', 'share', 'praise'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\app\Intel;
        // 实例化redis by Fire
        $options = config('cache');
        $options['prefix'] = 'gfw_topic';
        $options['select'] = 5;
        $this->redis = Cache::connect($options);
    }

    public function list()
    {
        $page    = input('page', 1);
        $limit   = 10;
        $user_id = input('user_id', '-1');
        $keyword = input('keyword', '');
        $recommend = input('recommend', '');
        $topic = input('topic', '');
        if ($user_id > -1) {
            $where['user_id'] = $user_id;
        }
        if ($recommend > 0){
            $where['recommendswitch'] = $recommend;
        }
        if ($keyword) {
            $where['content'] = ['like', '%'.$keyword.'%'];
        }
        if ($topic) {
            $where[] = ['exp', Db::raw("FIND_IN_SET('#$topic#', topicnames)")];
        }

        $where['verify'] = '1';
        $total = $this->model
            ->where($where)
            ->count();
        $list = $this->model->where($where)->order('id desc')->paginate($limit, $total, ['page' => $page]);
        if ($list) {
            foreach ($list as $k => $v) {
                $user                      = model('User')->field('nickname, avatar, group_id')->where('id', $v['user_id'])->find();
                $list[$k]['user']          = $user;
                $list[$k]['group']         = $user->group;
                $list[$k]['commentCount']  = $commentCount = model('app.IntelComment')->where('intel_id', $v['id'])->count();
                $list[$k]['filetype']      = model('app.IntelAttachment')->field('imagetype, filesize')->where('intel_id', $v['id'])->find();
                $list[$k]['updatetime']    = date('Y-m-d H:i', $v['updatetime']);
                $list[$k]['images']        = explode(',', $v['images']);
                $list[$k]['pv']            = $v['pvnum'] + $v['addpv'];
                $list[$k]['share']         = $v['sharenum'] + $v['addshare'];
                $list[$k]['praise']        = $v['praisenum'] + $v['addpraise'];

                // 缓存化记录话题pv
                $rand = mt_rand(2,30);
                $topic_ids = explode(',', $v['topic_ids']);
                foreach ($topic_ids as $vv) {
                    if ($vv) {
                        $this->redis->inc($vv.'_countPv');
                    }
                }

                $this->model->where('id', $v['id'])->setInc('pvnum');
                $this->model->where('id', $v['id'])->setInc('addpv', $rand);

                $newhouseLabelModel = model('NewhouseLabel');
                switch ( $v['rtype'] ) {
                    case '0':
                        $news = model('News')->field('id,title,image')->where('id', $v['rid'])->find();
                        if ($news) {
                            $list[$k]['linklist'] = $news;
                            $newsImage = explode(',', $news->image);
                            $list[$k]['linklist']['image'] = $newsImage[0];
                        }
                        break;
                    case '1':
                        $newhouse = model('Newhouse')->field('id,title,partnerlabel_id,covertype,houselabel_ids,house_image,businesslabel_ids,business_image')->where('id', $v['rid'])->find();
                        if ($newhouse) {
                            $list[$k]['linklist'] = $newhouse;
                            $newhouseLabel = $newhouseLabelModel->where('id', $newhouse->partnerlabel_id)->field('name,class')->find();
                            $list[$k]['linklist']['newhouselabel'] = $newhouseLabel->name;
                            $list[$k]['linklist']['labelClass'] = $newhouseLabel->class;
                            // 0=住宅,1=商业
                            if ( $newhouse->covertype ) {
                                // 商业
                                $list[$k]['linklist']['businessLabel'] = $newhouseLabelModel->where('id', 'in', $newhouse->businesslabel_ids)->field('name,class')->limit(3)->select();
                                $list[$k]['linklist']['image'] = $newhouse->business_image;
                            } else {
                                // 住宅
                                $list[$k]['linklist']['label'] = $newhouseLabelModel->where('id', 'in', $newhouse->houselabel_ids)->field('name,class')->limit(3)->select();
                                $list[$k]['linklist']['image'] = $newhouse->house_image;
                            }
                        }
                        break;
                    case '2':
                        $newhouseLayout = model('NewhouseLayout')->field('id,newhouse_id,title,attribute,label_ids,url')->where('id', $v['rid'])->find();
                        if ($newhouseLayout) {
                            $list[$k]['linklist'] = $newhouseLayout;
                            $newhouseName = model('Newhouse')->field('title')->where('id', $newhouseLayout->newhouse_id)->find();
                            $list[$k]['linklist']['newhouseName'] = $newhouseName->title;
                            $list[$k]['linklist']['label'] = $newhouseLabelModel->where('id', 'in', $newhouseLayout->label_ids)->field('name,class')->limit(3)->select();
                            $newhouseLayoutImages = explode(',', $newhouseLayout->url);
                            $list[$k]['linklist']['image'] = $newhouseLayoutImages[0];
                        }
                        break;
                    case '3':
                    case '4':
                        $esfHouse = model('EsfHouse')->field('id,title,lx,htype,nearby,images,propertyright,fanjia,jiawei,dianti,allarea,zx,fan,tin,weisheng,danwei,youxiao,orient,addlx,verify,xdel')->where('id', $v['rid'])->find();
                        if ($esfHouse) {
                            $list[$k]['linklist'] = $esfHouse;
                            $list[$k]['linklist']['title'] = $esfHouse->title;
                            $list[$k]['linklist']['htype'] = $esfHouse->htype;
                            $esfHouseImages = explode(',', $esfHouse->images);
                            $list[$k]['linklist']['image'] = $esfHouseImages[0];
                            $list[$k]['linklist']['jiage'] = $esfHouse->fanjia . $esfHouse->jiawei_text;
                            $list[$k]['linklist']['allarea'] = $esfHouse->allarea;
                            $list[$k]['linklist']['zx'] = $esfHouse->zx_text;
                        }
                        break;
                }
            }

            $this->success('操作成功', $list);
        } else {
            $this->error('请求错误');
        }
    }

    public function share()
    {
        $id = input('id');
        $res = $this->model->where('id', $id)->setInc('sharenum');

        if ($res !== false) {
            $intel = $this->model->get($id);
            $rand = mt_rand(2, 30);
            // 虚拟叠加
            $this->model->where('id', $id)->setInc('addshare', $rand);
            // 缓存化记录
            $topic_ids = explode(',', $intel->topic_ids);
            foreach ($topic_ids as $v) {
                if ($v) {
                    $this->redis->inc($v.'_countShare');
                }
            }

            $this->success('操作成功');
        } else {
            $this->error('请求错误');
        }
    }

    public function praise()
    {
        $id = input('id');
        $res = $this->model->where('id', $id)->setInc('praisenum');
        if ($res !== false) {
            $intel = $this->model->get($id);
            $rand = mt_rand(2, 30);
            // 虚拟叠加
            $this->model->where('id', $id)->setInc('addpraise', $rand);
            // 缓存化记录
            $topic_ids = explode(',', $intel->topic_ids);
            foreach ($topic_ids as $v) {
                if ($v) {
                    $this->redis->inc($v.'_countPraise');
                }
            }

            $this->success('操作成功');
        } else {
            $this->error('请求错误');
        }
    }

    public function delete()
    {
        $id = input('id');
        $res = $this->model->where('id', $id)->where('user_id', $this->auth->id)->find();
        if ($res) {
            $res->delete();
            $this->success('操作成功');
        } else {
            $this->error('请求错误');
        }
    }

    public function mylist()
    {
        $page    = input('page', 1);
        $limit   = 10;
        $verify = input('verify', '-1');

        $where['user_id'] = $this->auth->id;
        if ($verify > -1) {
            $where['verify'] = $verify;
        }
        $total = $this->model
            ->where($where)
            ->count();
        $list = $this->model->where($where)->order('id desc')->paginate($limit, $total, ['page' => $page]);
        if ($list) {
            foreach ($list as $k => $v) {
                $user = model('User')->field('nickname, avatar, group_id')->where('id', $v['user_id'])->find();
                $list[$k]['user']           = $user;
                $list[$k]['group']          = $user->group;
                $list[$k]['commentCount']   = $commentCount = model('app.IntelComment')->where('intel_id', $v['id'])->count();
                $list[$k]['filetype']       = model('app.IntelAttachment')->field('imagetype, filesize')->where('intel_id', $v['id'])->find();
                $list[$k]['updatetime']     = date('Y-m-d H:i', $v['updatetime']);
                $list[$k]['images']         = explode(',', $v['images']);
                $list[$k]['pv']             = $v['pvnum'] + $v['addpv'];
                $list[$k]['share']          = $v['sharenum'] + $v['addshare'];
                $list[$k]['praise']         = $v['praisenum'] + $v['addpraise'];

                $newhouseLabelModel = model('NewhouseLabel');
                switch ( $v['rtype'] ) {
                    case '0':
                        $news = model('News')->field('id,title,image')->where('id', $v['rid'])->find();
                        if ($news) {
                            $list[$k]['linklist'] = $news;
                            $newsImage = explode(',', $news->image);
                            $list[$k]['linklist']['image'] = $newsImage[0];
                        }
                        break;
                    case '1':
                        $newhouse = model('Newhouse')->field('id,title,partnerlabel_id,covertype,houselabel_ids,house_image,businesslabel_ids,business_image')->where('id', $v['rid'])->find();
                        if ($newhouse) {
                            $list[$k]['linklist'] = $newhouse;
                            $newhouseLabel = $newhouseLabelModel->where('id', $newhouse->partnerlabel_id)->field('name,class')->find();
                            $list[$k]['linklist']['newhouselabel'] = $newhouseLabel->name;
                            $list[$k]['linklist']['labelClass'] = $newhouseLabel->class;
                            // 0=住宅,1=商业
                            if ( $newhouse->covertype ) {
                                // 商业
                                $list[$k]['linklist']['businessLabel'] = $newhouseLabelModel->where('id', 'in', $newhouse->businesslabel_ids)->field('name,class')->limit(3)->select();
                                $list[$k]['linklist']['image'] = $newhouse->business_image;
                            } else {
                                // 住宅
                                $list[$k]['linklist']['label'] = $newhouseLabelModel->where('id', 'in', $newhouse->houselabel_ids)->field('name,class')->limit(3)->select();
                                $list[$k]['linklist']['image'] = $newhouse->house_image;
                            }
                        }
                        break;
                    case '2':
                        $newhouseLayout = model('NewhouseLayout')->field('id,newhouse_id,title,attribute,label_ids,url')->where('id', $v['rid'])->find();
                        if ($newhouseLayout) {
                            $list[$k]['linklist'] = $newhouseLayout;
                            $newhouseName = model('Newhouse')->field('title')->where('id', $newhouseLayout->newhouse_id)->find();
                            $list[$k]['linklist']['newhouseName'] = $newhouseName->title;
                            $list[$k]['linklist']['label'] = $newhouseLabelModel->where('id', 'in', $newhouseLayout->label_ids)->field('name,class')->limit(3)->select();
                            $newhouseLayoutImages = explode(',', $newhouseLayout->url);
                            $list[$k]['linklist']['image'] = $newhouseLayoutImages[0];
                        }
                        break;
                    case '3':
                    case '4':
                        $esfHouse = model('EsfHouse')->field('id,title,htype,images,fanjia,jiawei,allarea,zx')->where('id', $v['rid'])->find();
                        if ($esfHouse) {
                            $list[$k]['linklist'] = $esfHouse;
                            $list[$k]['linklist']['title'] = $esfHouse->title;
                            $list[$k]['linklist']['htype'] = $esfHouse->htype;
                            $esfHouseImages = explode(',', $esfHouse->images);
                            $list[$k]['linklist']['image'] = $esfHouseImages[0];
                            $list[$k]['linklist']['jiage'] = $esfHouse->fanjia . $esfHouse->jiawei_text;
                            $list[$k]['linklist']['allarea'] = $esfHouse->allarea;
                            $list[$k]['linklist']['zx'] = $esfHouse->zx_text;
                        }
                        break;
                }
            }

            $this->success('操作成功', $list);
        } else {
            $this->error('请求错误');
        }
    }

    public function release()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['user_id'] = $this->auth->id;
            $rule = [
                'user_id'   => 'require|gt:0',
                'content'   => 'require|checkContent:'
            ];
            $msg = [

                'user_id'           => '非会员不允许发布',
                'content.require'   => '情报内容不能为空'
            ];
            $data = [
                'user_id'   => $params['user_id'],
                'content'   => $params['content']
            ];
            $validate = new Validate($rule, $msg);
            $validate->extend('checkContent', function ($value) {
                if (strpos($value,'学位') !== false) {
                    return '标题包含敏感字：学位';
                }
                if (strpos($value,'学区') !== false) {
                    return '标题包含敏感字：学区';
                }
                if (strpos($value,'升值') !== false) {
                    return '标题包含敏感字：升值';
                }

                return true;
            });

            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
                return false;
            }
            // 匹配话题
            $topics = $this->topicMatches($params['content']);
            $params['content'] = str_replace($topics['old'], $topics['new'], $params['content']);

            $topic_ids = '';
            $topicNames = '';
            if ($topics != '') {
                foreach ($topics['new'] as $k => $v) {
                    $topicExist = TopicModel::get([
                        'name' => $v
                    ]);
                    if ($topicExist) {
                        $topic_ids .= $topicExist->id . ',';
                        $topicNames .= $topicExist->name . ',';
                    } else {
                        $res = TopicModel::create([
                            'name' => $v
                        ]);
                        $topic_ids .= $res->id . ',';
                        $topicNames .= $res->name . ',';
                    }
                }
            }

            $topicArr = explode( ',', rtrim($topic_ids, ',') );
            $params['topic_ids'] = implode(',', array_unique($topicArr));

            $topicNamesArr = explode( ',', rtrim($topicNames, ',') );
            $params['topicnames'] = implode(',', array_unique($topicNamesArr));
            if ( $params['vlog'] ) {
                $params['mediatype'] = 2;
            } elseif ($params['images']) {
                $params['mediatype'] = 1;
            }
            // 防止字段污染
            $params['verify'] = 0;
            $result = $this->model->allowField(true)->isUpdate(false)->save($params);
            $jobDate = [];
            if ($result !== false) {
                $jobDate['id']          = $this->model->id;
                $jobDate['user_id']     = $params['user_id'];
                $jobDate['content']     = $params['content'];
                $jobDate['images']      = $params['images'];
                $jobDate['vlog']        = $params['vlog'];
                $jobDate['topicArr']    = $topicArr;
                Queue::push('app\api\job\IntelVerify', $jobDate, 'intelVerifyJob');
                $this->success('发布成功，等待审核');
            } else {
                $this->error($this->model->getError());
            }
        }
    }

    public function commentPost()
    {
        if ($this->request->isPost()) {
            $params['intel_id'] = $this->request->post('intel_id');
            $params['reid'] = $this->request->post('reid', 0);
            $params['msg'] = $this->request->post('msg');
            $params['user_id'] = $this->auth->id;
            $params['nickname'] = $this->auth->nickname;
            $params['ip'] = $this->request->ip();
            $rule = [
                'user_id'   => 'require|gt:0',
                'intel_id'  => 'require|gt:0',
                'msg'       => 'require'
            ];
            $msg = [
                'user_id'   => '非会员不允许发布',
                'intel_id'  => '评论情报不存在',
                'msg'       => '评论内容不能为空'
            ];
            $data = [
                'user_id'   => $params['user_id'],
                'intel_id'  => $params['intel_id'],
                'msg'       => $params['msg']
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
                return false;
            }
            $msg = '{"Content":"'.base64_encode($params['msg']).'"}';
            $result = Hook::listen('text_moderation', $msg);
            if ($result[0]['Data']['EvilFlag'] > 0 || $result[0]['Data']['EvilType'] > 100) {
                $params['status'] = '0';
            } else {
                $params['status'] = '1';
            }
            $comment = model('app.intel_comment');
            $result = $comment->allowField(true)->isUpdate(false)->save($params);
            if ($result !== false) {
                if ($params['status']) {
                    // 缓存化记录
                    $intel = $this->model->get($params['intel_id']);
                    $topic_ids = explode(',', $intel->topic_ids);
                    foreach ($topic_ids as $v) {
                        if ($v) {
                            $this->redis->inc($v.'_countComment');
                        }
                    }

                    $this->success('评论成功');
                } else {
                    $this->error('请文明评论，谢谢');
                }
            } else {
                $this->error($comment->getError());
            }
        }
    }

    /**
     * 匹配话题字样
     * @param  string $s 传入内容字段
     * @return array  ['old'] or ['new']
     *
     * 处理内容的时候使用，话题就用 返回的值 $r['new'] 取遍历取值是否添加话题，获取回话题id值 1,3格式存进情报表
     * $new_content = str_replace($r['old'], $r['new'], $content);
     */
    protected function topicMatches($s){
        // 获取内容全部匹配话题出来
        preg_match_all("/#[^#]+#/", $s, $matches);
        // 匹配到没有话题
        if( !$matches[0] ){
            return false;
        }
        // 重新生成一个数组
        $trimTopicList = [];
        if( is_array($matches) ){
            foreach ($matches[0] as $k => $v) {
                // 再次匹配去掉全部是空格的
                preg_match("/[^#]+/", $v, $matche);
                if( !ctype_space($matche[0]) ){
                    // 没有去掉的话题原文， 拿来做根据替换掉内容里面的话题
                    $trimTopicList['old'][] = '#' . $matche[0] . '#';
                    // 去掉# 左右两侧的空格 # 只允许两字中间带有空格
                    $trimTopicList['new'][] = '#' . trim( $matche[0], " " ) . '#';
                }
            }
        }
        return $trimTopicList;
    }
}
